package org.example.controller;


import com.google.common.collect.ImmutableMap;
import org.example.dto.DeptDto;
import org.example.entity.SysDept;
import org.example.model.DeptModel;
import org.example.service.SysDeptService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dept")
public class SysDeptController {

    @Resource
    private SysDeptService sysDeptService;

    /**
     * 前端使用的是 axios, axios除了GET请求，其余的 Content-Type application/json
     * @return
     */
    @GetMapping
    public List<DeptModel> showAllByTree() {

//        System.out.println("dept-controller返回的数据为：------------"+sysDeptService.getDeptTree());

        return sysDeptService.getDeptTree();
    }

    //删除数据
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable("id") Long id) {
//        System.out.println("删除-------------->");
        sysDeptService.delete(id);
        return ImmutableMap.of("code", 1, "msg", "success");

    }

    //获取编辑数据回显
    @GetMapping("/{id}")
    public SysDept getById(@PathVariable("id") Long id) {

//        System.out.println("edit---->id的值为："+id);
        return sysDeptService.getById(id);
    }

    //编辑数据

    @PutMapping
    public Map<String, Object> edit(@RequestBody DeptDto deptDto) {
//        System.out.println("controller----->edit---put"+deptDto);
        sysDeptService.edit(deptDto);
        return ImmutableMap.of("code", 1, "msg", "success");
    }

    //添加数据
    @PostMapping
    public Map<String, Object> add(@RequestBody DeptDto deptDto,Principal principal) {
//        sysDeptService.add(deptDto);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String format1 = simpleDateFormat.format(new Date());
//        val format = format1
        deptDto.setCreateTime(new Date());
        System.out.println("controller-add-deptDto.getParentId()"+deptDto.getParents());
        if(deptDto.getParents().size()==0){
            List<Integer> list = new ArrayList<>();
            deptDto.setParentId(0);

            deptDto.setParents(list);

        }
        else{
            List<Integer> list =deptDto.getParents();



            Integer len = list.size();


            deptDto.setParentId(list.get(len-1));

        }
        deptDto.setCreateBy(principal.getName());
        sysDeptService.add(deptDto);
//        System.out.println("controller里的deptdto:------->>"+deptDto.getCreateBy());
        return ImmutableMap.of("code", 1, "msg", "success");
    }

}
